from fastapi import APIRouter, HTTPException, Depends, Query
from crud.calorie.Calorie_Manage import (
    get_user_calories,
    add_food_to_meal,
    get_meals_by_date,
)
from crud.calorie.Food_Info import get_foods_info
from routers.models import MealsResponse, Food, MealRecord
from routers.user import get_current_user_id
from typing import Optional, List

router = APIRouter(tags=["卡路里计算"])


# 获取用户的热量统计
@router.get("/calorieInfo")
async def get_user_calories_route(
    user_id: str = Depends(get_current_user_id),
    date: Optional[str] = Query(None, description="统计日期，格式为 YYYY-MM-DD"),
):
    """
    获取用户的热量统计数据

    Args:
    - user_id: 从依赖注入中获取的用户 ID
    - date: 查询参数，指定日期（可选）

    Returns:
    - 用户的热量统计数据
    """
    try:
        # 传递日期参数给业务逻辑层
        result = get_user_calories(user_id, date)

        if result is None:
            raise HTTPException(status_code=404, detail="User calories data not found.")

        return result
    except Exception as e:
        print(f"Error: {e}")
        raise HTTPException(status_code=500, detail="An internal error occurred.")


# 获取指定日期的餐食记录
@router.get("/getMealRecords")
async def get_meals(
    user_id: str = Depends(get_current_user_id),
    date: Optional[str] = Query(None, description="统计日期，格式为 YYYY-MM-DD"),
):
    """
    获取指定用户在某一天的餐食记录。

    :param user_id: 当前用户的ID，自动通过依赖注入获取
    :param date: 统计日期，格式为 'YYYY-MM-DD'，默认为当天
    :return: 按餐次分类的餐食记录数据
    """
    try:
        # 调用获取餐食记录的函数
        meals_data = get_meals_by_date(user_id, date)

        # 如果没有记录，返回 404 错误
        if not meals_data:
            raise HTTPException(
                status_code=404, detail=f"No meal records found for date {date}."
            )

        # 返回数据，符合 FastAPI 的响应模型
        return {"meals": meals_data}
    except HTTPException as http_err:
        # 返回自定义 HTTP 异常
        raise http_err
    except Exception as e:
        # 捕获其他异常并返回 500 错误
        raise HTTPException(
            status_code=500,
            detail=f"An error occurred while retrieving meals: {str(e)}",
        )


@router.post("/saveMealRecord")
async def add_food_to_meal_route(
    record: MealRecord,
    user_id: str = Depends(get_current_user_id),
):
    try:
        # 调用服务层逻辑处理
        result = add_food_to_meal(user_id, record)

        # 返回统一的响应格式
        return {
            "success": True,
            "message": result.get("message"),
        }
    except Exception as e:
        # 捕获异常并返回错误信息
        return {
            "success": False,
            "error": str(e),
        }


@router.get("/getFoodsInfo", response_model=List[Food])
async def get_foods():
    try:
        foods_data = get_foods_info()
        foods = [Food(**food) for food in foods_data]

        if not foods:
            raise HTTPException(status_code=404, detail="No food found")
        return foods
    except Exception as e:
        raise HTTPException(status_code=500, detail="An internal error occurred")
